<template>
  <el-scrollbar max-height="83vh">
    <vab-card shadow="always" v-loading="loading">
      <header class="flex_sb_wrap">
        <p>组织架构</p>
        <div class="btn flex">
          <VabAuthButton title="复制" @click="handleModifyNode('copy')" />
          <VabAuthButton
            title="新建"
            @click="handleModifyNode('new')"
            style="margin-right: 4px"
          />
          <vab-icon
            :icon="isOpenTree ? 'arrow-down-s-fill' : 'arrow-up-s-fill'"
            @click="handleOpen"
          />
        </div>
      </header>
      <el-tree
        draggable
        node-key="id"
        ref="treeRef"
        :data="dataSource"
        :props="{
          label: 'name',
          children: 'child',
        }"
        v-if="isOpenTree"
        :default-expand-all="isOpenTree"
        @node-click="handleNode"
      />
    </vab-card>
  </el-scrollbar>
</template>

<script setup lang="ts">
  import { customerCategory } from '~/src/api/dms/customer'

  defineOptions({
    name: 'MenuTree',
  })

  /**
   * @var
   */
  const proxy: any = getCurrentInstance()?.proxy
  const storage: any = localStorage.getItem('userInfo')
  const userInfo: any = JSON.parse(storage)

  const loading = ref(false) //加载
  const isOpenTree = ref(true) //是否展开树状结构
  const dataSource = ref<any>([]) //数据
  const nodeMode = ref<any>(null) //节点

  /**
   * @method
   */

  const emit = defineEmits(['handleModifyNode', 'handleNode'])

  const handleModifyNode = (type: string) => {
    if (!nodeMode.value && type == 'copy') {
      proxy.$Message('请选择要复制的客户', 'warning')
      return
    }

    emit('handleModifyNode', nodeMode.value, type)
  }
  // 展开关闭
  const handleOpen = () => {
    isOpenTree.value = !isOpenTree.value
  }
  //操作节点 展示详情
  const handleNode = (data: any) => {
    nodeMode.value = data
    emit('handleNode', data)
  }

  // 获取树状数据
  const _GetTreeList = async () => {
    loading.value = true
    try {
      const res = await customerCategory({ group_cust_id: userInfo.uid })
      dataSource.value = res.data
      loading.value = false
    } catch (error) {}
  }

  /**
   * @实例
   */

  onMounted(() => {
    _GetTreeList()
  })

  defineExpose({
    _GetTreeList,
  })
</script>
